package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ConstantEnum;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.TbGoodsService;
import com.dongdongshop.service.TbItemCatService;
import com.dongdongshop.service.TbItemService;
import com.dongdongshop.service.TbTypeTemplateService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("good")
public class TbGoodsController {

    @Reference
    private TbGoodsService tbGoodsService;

    @Reference
    private TbItemCatService tbItemCatService;

    @Reference
    private TbTypeTemplateService tbTypeTemplateService;

    @Reference
    private TbItemService tbItemService;



    @Reference
    private com.dongdongshop.service.TbSpecificationOption tbSpecificationOption;


    @RequestMapping("goodsEdit")
    public String goodsEdit(Model model){
        return "/admin/goods_edit";
    }

    @RequestMapping("getCatInfo1")
    @ResponseBody
    public Result getCatInfo1(Long parentId){
        List<TbItemCat> cat1 = tbItemCatService.getCatInfo1(parentId);
        return Result.build(ConstantEnum.SUCCESS).setResult(cat1);
    }

    @RequestMapping("getTypeId")
    @ResponseBody
    public Result getTypeId(Long id){
        TbItemCat typeId = tbItemCatService.getTypeId(id);
        return Result.build(ConstantEnum.SUCCESS).setResult(typeId);
    }

    @RequestMapping("getTypeTemplate")
    @ResponseBody
    public Result getTypeTemplate(Long id){
        TbTypeTemplate type = tbTypeTemplateService.getBrand(id);
        return Result.build(ConstantEnum.SUCCESS).setResult(type);
    }

    @RequestMapping("insertGoodInfo")
    @ResponseBody
    public Result insertGoodInfo(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc,String tbItem){
        //获取商家Id
        TbSeller principal =(TbSeller) SecurityUtils.getSubject().getPrincipal();
        tbGoods.setSellerId(principal.getSellerId());
        String nickName = principal.getNickName();
        List<TbItem> itemList = JSONObject.parseArray(tbItem,TbItem.class);
        tbGoodsService.insertGoodInfo(tbGoods,tbGoodsDesc,itemList,nickName);
        return Result.build(ConstantEnum.SUCCESS);
    }

    @RequestMapping("upLoadFile")
    @ResponseBody
    public Map<String, String> upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile) throws IOException {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。
        // 以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String http = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";      // oss全球有很多服务器   我们需要上传到那个地区的服务器上
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tEVQsgkbksvSgctnbWY";
        String accessKeySecret = "bEAnAFBbm5hDubJZuA6bUL7fG1tCNV";

        String bucketName = "dongdongshop-x-fg0";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 填写字符串。
//        String content = "Hello OSS";
        // 转换成流的方式
        InputStream stream = myFile.getInputStream();
        //
        String filename = myFile.getOriginalFilename();


        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest =
                new PutObjectRequest(bucketName, filename, stream);

        // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        Map<String,String> url = new HashMap<>();
        url.put("imgUrl", http+bucketName+"."+endpoint+"/"+filename);
        return url;
    }









    //          商品审核

    @RequestMapping("goods")
    public String goods(Model model){
        return "admin/goods";
    }

    @RequestMapping("getGoodsInfo")
    @ResponseBody
    public Result getGoodsInfo(TbGoods tbGoods){
        TbSeller seller = (TbSeller) SecurityUtils.getSubject().getPrincipal();
        String sellerId = seller.getSellerId();
        Result result = tbGoodsService.getGoodList(sellerId, tbGoods);
        return result;
    }

    //提交审核
    @RequestMapping("updateBatch")
    @ResponseBody
    public Result updateBatch(String[] ids){
        Result result = tbGoodsService.updateBatch(ids, "3");
        return result;
    }

    //批量屏蔽
    @RequestMapping("deleteBatch")
    @ResponseBody
    public Result deleteBatch(String[] ids){
        Result result = tbGoodsService.deleteBatch(ids);
        return result;
    }



    @RequestMapping("getSpecInfo")
    @ResponseBody
    public Result getSpecInfo(Long id){
        TbTypeTemplate type = tbTypeTemplateService.getBrand(id);
        String specIds = type.getSpecIds();
        List<TbSpecification> specifications = JSONObject.parseArray(specIds, TbSpecification.class);
        List<SpecVO> voList = new ArrayList<>();
        for (TbSpecification specification : specifications) {
            // 根据规格ID 查询  tb_specification_option
            List<TbSpecificationOption> options = tbSpecificationOption.getSpecOptionInfo(specification.getId());
            SpecVO vo = new SpecVO();
            vo.setTbSpecification(specification);
            vo.setList(options);
            voList.add(vo);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(voList);
    }






}
